package info.batcloud.fanli.api.controller;

import info.batcloud.fanli.core.domain.BusinessResponse;
import info.batcloud.fanli.core.domain.Result;
import info.batcloud.fanli.core.dto.UserDTO;
import info.batcloud.fanli.core.enums.UserLevel;
import info.batcloud.fanli.core.exception.BizException;
import info.batcloud.fanli.core.helper.SecurityHelper;
import info.batcloud.fanli.core.service.UserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {


    @Inject
    private UserService userService;

    @PostMapping("/phone-bind")
    @PreAuthorize("hasRole('USER')")
    public Object bindPhone(UserService.BindPhoneParam param) {
        param.setUserId(SecurityHelper.loginUserId());
        return BusinessResponse.ok(userService.bindPhone(param));
    }

    @PostMapping("/field")
    @PreAuthorize("hasRole('USER')")
    public Object updateField(UserService.FieldUpdateParam param) {
        param.setUserId(SecurityHelper.loginUserId());
        return BusinessResponse.ok(userService.updateUserField(param));
    }

    @PostMapping("/weixin-bind/{weixinCode}")
    @PreAuthorize("hasRole('USER')")
    public Object bindWeixin(@PathVariable String weixinCode) {
        return BusinessResponse.ok(userService.bindWeixin(SecurityHelper.loginUserId(), weixinCode));
    }

    @GetMapping("/level")
    @PreAuthorize("hasRole('USER')")
    public Object userLevel() {
        return BusinessResponse.ok(userService.findUserLevelByUserId(SecurityHelper.loginUserId()));
    }

    @PutMapping("/check-user-directly-upgrade/{id}")
    public Object checkUserDirectlyUpgrade(@PathVariable long id) {
        UserService.CheckUserDirectlyUpgradeResult result = userService.checkUserDirectlyUpgrade(id);
        return BusinessResponse.ok(result);
    }

    @GetMapping("/is-plus")
    @PreAuthorize("hasRole('USER')")
    public Object isPlus() {
        return BusinessResponse.ok(userService.isUserLevel(SecurityHelper.loginUserId(), UserLevel.PLUS));
    }

    @PutMapping("/modify-pwd")
    @PreAuthorize("hasRole('USER')")
    public Object modifyPwd(UserService.ModifyPwdParam param, BindingResult result) {
        if (result.hasErrors()) {
            throw new BizException("参数错误，请检查!");
        }
        param.setUserId(SecurityHelper.loginUserId());
        Result rs = userService.modifyPassword(param);
        return BusinessResponse.ok(rs);
    }

    @GetMapping("/location")
    public Object getLocation() {
        Map<String, Object> map = new HashMap<>();
        if (SecurityHelper.loginUserId() != null) {
            UserDTO user = userService.findById(SecurityHelper.loginUserId());
            map.put("city", user.getCity());
            map.put("cityId", user.getCityId());
            map.put("districtId", user.getDistrictId());
            map.put("district", user.getDistrict());
        }
        return BusinessResponse.ok(map);
    }

    @PutMapping("/district/{id}")
    @PreAuthorize("hasRole('USER')")
    public Object setDistrict(@PathVariable long id) {
        UserDTO user = userService.setUserDistrict(SecurityHelper.loginUserId(), id);
        Map<String, Object> map = new HashMap<>();
        map.put("city", user.getCity());
        map.put("cityId", user.getCityId());
        map.put("districtId", user.getDistrictId());
        map.put("district", user.getDistrict());
        return BusinessResponse.ok(map);
    }

    @PutMapping("/upgrade-user-level")
    @PreAuthorize("hasRole('USER')")
    public Object upgradeUserLevel() {
        UserService.UserLevelCheckUpgradeResult result = userService.checkUpgradeUserLevel(SecurityHelper.loginUserId());
        Map<String, Object> map = new HashMap<>();
        map.put("userLevel", result.getUserLevel());
        map.put("userLevelTitle", result.getUserLevel().getTitle());
        map.put("success", result.isSuccess());
        map.put("errMsg", result.getErrMsg());
        map.put("orderId", result.getOrderId());
        map.put("waitPay", result.isWaitPay());
        map.put("upgradeFeeList", result.getUpgradeFeeList());
        return BusinessResponse.ok(map);
    }

    @GetMapping("/taobao-relation-id")
    public Object getTaobaoRelationId() {
        return BusinessResponse.ok(userService.findOrGenerateTaobaoRelationId(SecurityHelper.loginUserId()));
    }

    @GetMapping("/invite-pic/{invitationCode}")
    public String sharePicGenPic(@PathVariable String invitationCode, @RequestParam String bgImg, HttpServletResponse response) throws IOException {
        response.setContentType("image/jpg");
        response.setHeader("Content-Type", "image/jpg");
        try {
            userService.genInvitationShareSvg(invitationCode,
                    bgImg, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.getOutputStream().close();
        response.flushBuffer();
        return null;
    }
}
